package com.cpfmat.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cpfmat.common.Contains;
import com.cpfmat.entity.Article;
import com.cpfmat.entity.SystemMenu;
import com.cpfmat.service.IArticleService;
import com.cpfmat.service.ISystemMenuService;
import com.cpfmat.vo.CustomArticle;

@Controller
public class MainController {
	@Autowired
	private IArticleService articleService;
	@Autowired
	private ISystemMenuService menuService;
	
	@RequestMapping(path = "/news")
	public ModelAndView news(@RequestParam(name = "keyword", required = false) String keyword,
			@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,String all) throws Exception {
		String type = "news";
		String path = "/new/list";
		ModelAndView view = common(type, keyword, pageNum, path);
		
		return view;
	}
	
	@RequestMapping(path = "/platform")
	public ModelAndView platform(@RequestParam(name = "keyword", required = false) String keyword,
			@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,String all) throws Exception {
		String type = "platform";
		String path = "/new/list";
		ModelAndView view = common(type, keyword, pageNum, path);
		
		return view;
	}
	
	@RequestMapping(path = "/authority")
	public ModelAndView authority(@RequestParam(name = "keyword", required = false) String keyword,
			@RequestParam(name = "pageNum", defaultValue = "1") int pageNum,String all) throws Exception {
		String type = "authority";
		String path = "/new/list";
		ModelAndView view = common(type, keyword, pageNum, path);
		
		return view;
	}
	
	private ModelAndView common(String type,String keyword,int pageNum,String pagePath) {
		ModelAndView view = new ModelAndView(pagePath);
		SystemMenu systemMenu = Contains.menuKeyMap.get(type);
		
		Page<CustomArticle> page = articleService.getPage(keyword, systemMenu.getSeqId(), null, pageNum, Contains.PAGE_SIZE);
		view.addObject("page",page);
		view.addObject("type",type);
		
		return view;
	}
	
	/**
	 * 以前用来查询页面用的 包括子栏目 推荐等的查询 现在暂时不用了
	 * @param type
	 * @param all
	 * @param keyword
	 * @param pageNum
	 * @param pagePath
	 * @return
	 * @throws Exception
	 */
	protected ModelAndView common(String type,String all,String keyword,int pageNum,String pagePath) throws Exception{
		ModelAndView view = new ModelAndView(pagePath);
		SystemMenu systemMenu = Contains.menuKeyMap.get(type);
		
		if(type.equals(all) && systemMenu != null){
			Page<CustomArticle> page = articleService.getPage(keyword, systemMenu.getSeqId(), null, pageNum, Contains.PAGE_SIZE);
			Page<CustomArticle> recommendPage = articleService.getRecommendPage(systemMenu.getSeqId(), null, 1, Contains.RECOMMEND_PAGE_SIZE);
			view.addObject("page",page);
			view.addObject("recommendPage",recommendPage);
		}
		else{
			EntityWrapper<SystemMenu> menu = new EntityWrapper<SystemMenu>();
			menu.eq("`KEY`", type);
			menu.eq("DEL_FLAG", 0);
			SystemMenu selectOne = menuService.selectOne(menu);
			String parentColumnId = null;
			if(selectOne != null){
				parentColumnId = selectOne.getSeqId();
			}
			if(parentColumnId == null){
				throw new Exception("找不到" + type + "对应的菜单信息");
			}
			
			Page<CustomArticle> page = null;
			Page<CustomArticle> recommendPage = null;
			if(systemMenu == null) {
				page = articleService.getPage(keyword, null, parentColumnId, pageNum, Contains.PAGE_SIZE);
				recommendPage = articleService.getRecommendPage(null, parentColumnId, 1, Contains.RECOMMEND_PAGE_SIZE);
				
				if("list".equals(all)) {
					// 添加全部菜单
					selectMainMenuList(view);
				}
				else {
					menu = new EntityWrapper<SystemMenu>();
					menu.eq("PARENT_ID",parentColumnId);
					menu.eq("DEL_FLAG", 0);
					menu.orderBy("ORDER_NUM", true);
					
					List<SystemMenu> menuList = menuService.selectList(menu);
					view.addObject("menuList", menuList);
				}
			}
			else {
				page = articleService.getPage(keyword, parentColumnId, null, pageNum, Contains.PAGE_SIZE);
				recommendPage = articleService.getRecommendPage(parentColumnId, null, 1, Contains.RECOMMEND_PAGE_SIZE);

				if("list".equals(all)) {
					// 添加全部菜单
					selectMainMenuList(view);
				}
				else {
					menu = new EntityWrapper<SystemMenu>();
					menu.eq("PARENT_ID",selectOne.getParentId());
					menu.eq("DEL_FLAG", 0);
					menu.orderBy("ORDER_NUM", true);
					
					List<SystemMenu> menuList = menuService.selectList(menu);
					view.addObject("menuList", menuList);
				}
			}
			
			view.addObject("page",page);
			view.addObject("recommendPage",recommendPage);
		}
		
		// 输入流读取配置文件
		String imagePath = readImagePathFromProperties(type);
		if(imagePath == null){
			String parentId = systemMenu.getParentId();
			SystemMenu parentMenu = menuService.selectById(parentId);
			if(parentMenu == null){
				imagePath = readImagePathFromProperties("default");
			}
			else{
				imagePath = readImagePathFromProperties(parentMenu.getKey());
				if(imagePath == null) imagePath = readImagePathFromProperties("default");
			}
			
		}
		view.addObject("imagePath",imagePath);
		
		view.addObject("type",type);
		view.addObject("all",all);
		view.addObject("keyword",keyword);
		
		return view;
	}
	
	private void selectMainMenuList(ModelAndView view) {
		EntityWrapper<SystemMenu> menu = new EntityWrapper<SystemMenu>();
		menu.isNull("PARENT_ID");
		menu.eq("IS_NAV", 1);
		menu.notIn("`KEY`", "contact,about");
		menu.eq("DEL_FLAG", 0);
		menu.orderBy("ORDER_NUM", true);
		
		List<SystemMenu> menuList = menuService.selectList(menu);
		List<SystemMenu> resultList = new ArrayList<SystemMenu>();
		Iterator<SystemMenu> iterator = menuList.iterator();
		while(iterator.hasNext()){
			SystemMenu obj = iterator.next();
			if(obj.getIsColumn() == 1 || "coordination".equals(obj.getKey())
					|| "project".equals(obj.getKey()) || "news".equals(obj.getKey())){
				resultList.add(obj);
			}
		}
		view.addObject("menuList", resultList);
	}
	
	private String readImagePathFromProperties(String key){
		try {
			Properties properties = new Properties();
			properties.load(this.getClass().getResourceAsStream("/listPageImg.properties"));
			
			return properties.getProperty(key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 返回关于我们页面
	 * @return
	 */
	@RequestMapping(path = "/about")
	public ModelAndView about() {
		ModelAndView view = new ModelAndView("/new/about");

		Page<CustomArticle> page = articleService.getPage(null, Contains.menuKeyMap.get("about").getSeqId(), null, 1,
				1);

		if (page != null && page.getRecords() != null && page.getRecords().get(0) != null) {
			CustomArticle article = page.getRecords().get(0);
			CustomArticle result = articleService.detailWithAttachments(article.getSeqId());
			
			Article updateArticle = new Article();
			updateArticle.setSeqId(article.getSeqId());
			updateArticle.setViewCounts(article.getViewCounts() + 1);
			articleService.updateById(updateArticle);
			
			view.addObject("article", result);
		}

		return view;
	}

	@RequestMapping(path = "/contact")
	public ModelAndView contact() {
		ModelAndView view = new ModelAndView("/column/contact");

		return view;
	}
}
